package com.honghu.villagepost.activity.fragment

import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.viewpager.widget.ViewPager
import com.blankj.utilcode.util.ActivityUtils
import com.google.android.material.appbar.AppBarLayout
import com.honghu.villagepost.R
import com.honghu.villagepost.activity.ContactUsActivity
import com.honghu.villagepost.activity.GoodsCidListActivity
import com.honghu.villagepost.activity.SearchActivity
import com.honghu.villagepost.adapter.BaseFragmentStateAdapter
import com.honghu.villagepost.adapter.ClassifyAdapter
import com.honghu.villagepost.adapter.ImageAdapter
import com.honghu.villagepost.adapter.MarqueeViewAdapter
import com.honghu.villagepost.api.ApiService
import com.honghu.villagepost.base.BaseFragment
import com.honghu.villagepost.callback.DialogCallback
import com.honghu.villagepost.callback.LzyResponse
import com.honghu.villagepost.entity.BannerEntity
import com.honghu.villagepost.entity.Classify
import com.lzy.okgo.model.Response
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.wuhenzhizao.sku.utils.ScreenUtils
import com.youth.banner.indicator.CircleIndicator
import kotlinx.android.synthetic.main.fragment_city.fl_search
import kotlinx.android.synthetic.main.fragment_city.iv_msg
import kotlinx.android.synthetic.main.fragment_city.marquee_view
import kotlinx.android.synthetic.main.fragment_city.root_layout
import kotlinx.android.synthetic.main.fragment_village.*


/**
 * @author: mqwang
 * @create: 1/26/21 10:19 AM
 * @Description: 逛农村fragment
 */
class VillageFragment : BaseFragment(), ViewPager.OnPageChangeListener {

    private val classifyAdapter: ClassifyAdapter by lazy {
        ClassifyAdapter()
    }

    private val imageAdapter: ImageAdapter by lazy {
        ImageAdapter(bannerEntities)
    }

    private val tabFragmentList: MutableList<Fragment> = ArrayList()

    private val bannerEntities: MutableList<BannerEntity> = ArrayList()

    override fun initViews(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val view = inflater!!.inflate(R.layout.fragment_village, container, false)
        return view
    }

    override fun initData() {
        val statusBarHeight = ScreenUtils.getStatusBarHeight(activity)
        root_layout.setPadding(0, statusBarHeight, 0, 0)

        rv_classify.adapter = classifyAdapter
        rv_classify.layoutManager = GridLayoutManager(activity, 5)

        val bannerEntity = BannerEntity()
        bannerEntity.picRes = R.mipmap.ic_banner_city
        bannerEntities.add(bannerEntity)
        banner.adapter = imageAdapter
        banner.addBannerLifecycleObserver(this)
        banner.indicator = CircleIndicator(activity)
        imageAdapter.notifyDataSetChanged()

        val data: MutableList<String> = ArrayList()
        data.add("神奇宝贝（精灵宝可梦）有哪些著名的梗？")
        data.add("我翻开自我保护的书，上面只写了两个大字：证据")
        data.add("接纳自己，是无条件地爱，包括爱所有的痛苦")
        data.add("3 岁前，世界对待孩子的一切，都会给他们留下深刻的第一印象")
        data.add("担心今天没锻炼，现在站起来，做一组完美深蹲")

        marquee_view?.setAdapter(MarqueeViewAdapter(data, activity))
        //刷新数据
        //marqueeViewAdapter.setData(data);

        classifyAdapter.setOnItemClickListener { adapter, view, position ->
            var goods = adapter.getItem(position) as Classify
            GoodsCidListActivity.self(activity!!, goods.id, goods!!.name)

        }

        fl_search.setOnClickListener {
            ActivityUtils.startActivity(SearchActivity::class.java)
        }

        iv_msg.setOnClickListener {
            ActivityUtils.startActivity(ContactUsActivity::class.java)
        }

        smart_refresh.setEnableLoadMore(false)
        smart_refresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                onRefreshFragment()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
            }

        })

        var mTitles: MutableList<String> = ArrayList()
        mTitles.add("猜你喜欢")
        mTitles.add("附近商家")
        tabFragmentList.add(HomeLikeFragment.newInstance(HomeNearShopFragment.SHOP_TYPE_VILLAGE))
        tabFragmentList.add(HomeNearShopFragment.newInstance(HomeNearShopFragment.SHOP_TYPE_VILLAGE))
        content_vp.setAdapter(BaseFragmentStateAdapter(childFragmentManager, tabFragmentList, mTitles))
        content_vp.addOnPageChangeListener(this)

        to_tv.setOnClickListener {
            content_vp.setCurrentItem(0)
        }

        near_shop_tv.setOnClickListener {
            content_vp.setCurrentItem(1)
        }

        appBar.addOnOffsetChangedListener(object : AppBarLayout.OnOffsetChangedListener {
            override fun onOffsetChanged(appBarLayout: AppBarLayout?, offset: Int) {

                if (offset >= 0) {
                    setEnableRefresh(true)
                } else {
                    setEnableRefresh(false)
                }
            }

        })

        initTabIndicator(0)
        getData()
    }

    fun getData() {
        ApiService.goods_category(this, HomeNearShopFragment.SHOP_TYPE_VILLAGE, object : DialogCallback<LzyResponse<List<Classify>>>() {
            override fun onSuccess(response: Response<LzyResponse<List<Classify>>>?) {
                classifyAdapter.setNewData(response!!.body().data)
            }
        })
    }

    private fun setEnableRefresh(enableRefresh: Boolean) {
        for (fragment in tabFragmentList) {
            if (fragment is HomeLikeFragment) {
                (fragment as HomeLikeFragment).setEnableRefresh(enableRefresh)
            } else if (fragment is HomeNearShopFragment) {
                (fragment as HomeNearShopFragment).setEnableRefresh(enableRefresh)
            }
        }
    }

    private fun onRefreshFragment() {
        if (tabFragmentList != null) {
            val fragment = tabFragmentList.get(content_vp.currentItem)
            if (fragment != null) {
                if (fragment is HomeLikeFragment) {
                    (fragment as HomeLikeFragment).onAutoRefresh()
                } else if (fragment is HomeNearShopFragment) {
                    (fragment as HomeNearShopFragment).onAutoRefresh()
                }
            }
        }
    }

    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
    }

    override fun onPageSelected(position: Int) {
        initTabIndicator(position);
    }

    private fun initTabIndicator(position: Int) {
        if (position == 0) {
            to_tv.isSelected = true;
            to_tv.setTypeface(Typeface.DEFAULT_BOLD)
            near_shop_tv.isSelected = false;
            near_shop_tv.setTypeface(Typeface.DEFAULT)
        } else {
            to_tv.isSelected = false;
            to_tv.setTypeface(Typeface.DEFAULT)
            near_shop_tv.isSelected = true;
            near_shop_tv.setTypeface(Typeface.DEFAULT_BOLD)
        }
    }

    override fun onPageScrollStateChanged(state: Int) {
    }

    fun onFinishRefresh() {
        smart_refresh?.finishRefresh()
    }
}